package com.chuanye.cluster.message;

import com.chuanye.cluster.models.Preheat_Request;
import com.chuanye.cluster.models.Preheat_Response;
import com.chuanye.cluster.models.YY_DATA_AUTO_Request;
import com.chuanye.cluster.pojo.ResultDto;
import com.chuanye.cluster.models.YY_DATA_AUTO_List_Request;
import com.chuanye.cluster.pojo.SocketMultipleRegisterDto;
import com.chuanye.cluster.utils.GsonUtils;
import com.chuanye.cluster.utils.ProsUtils;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

@Api(value = "DevSignalController",description = "设备消息集线器接口")
@RequestMapping("DevSignal")
@RestController
public class DevSignalController {




    @Autowired
    private void setChatService(RedisUtils redisTampate) {
        DevSignalController.redisTampate = redisTampate;
    }

    @Autowired
    private ServerConfig serverConfig;

    private static Logger log = LoggerFactory.getLogger(DevSignalController.class);

    private static String serverProPath="socketServer.properties";

    public static String pushDataKey="devSignal";

    private static RedisUtils redisTampate;

    @ApiOperation(value = "数据推送")
    @PostMapping("/SD_YY_DATA_AUTO")
    public ResultDto<Integer> pushData(@RequestBody YY_DATA_AUTO_List_Request request) {
        ResultDto<Integer> result =new  ResultDto<Integer>();
        try {
            if(request!=null&&request.getList()!=null &&request.getList().size()>0){
                for (YY_DATA_AUTO_Request s: request.getList()) {
                    Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                    String key=pushDataKey+"_"+s.getSTCD()+"_"+s.getItemID();
                    ArrayList<YY_DATA_AUTO_Request> list=new ArrayList<YY_DATA_AUTO_Request>();
                    list.add(s);
                    String existDataJson=redisTampate.get(key);
                    if(existDataJson!=null && !existDataJson.equals("")) {
                        ArrayList<YY_DATA_AUTO_Request>  existList= gson.fromJson(existDataJson,new TypeToken<ArrayList<YY_DATA_AUTO_Request>>(){}.getType());
                        existList.add(s);
                        this.sort(existList);
                        //保留200条最新数据
                        if(existList.size()>200) {
                            int ignoreCount=existList.size()-200;
                            for (int i=ignoreCount;i<existList.size();i++)
                            {
                                list.add(existList.get(i));
                            }
                        }
                        else{
                            list.addAll(existList);
                        }
                    }
                    else {
                        list.add(s);
                    }
                    this.sort(list);
                    String dataJson= gson.toJson(list);

                    redisTampate.set(key,dataJson);
                }
                result.setStatus(1);
                result.setMessage("Requst Is Success");
                result.setFirstParam(1);
            }else {
                result.setStatus(201);
                result.setMessage("Request Data Is Null");
                result.setFirstParam(1);
            }
        }catch (Exception e) {
            //TODO: handle exception
            log.error(e.getMessage());
            result.setStatus(500);
            result.setMessage("/Dev/SD_YY_DATA_AUTO Server Error");
            result.setFirstParam(0);
        }
        return  result;
    }


    @ApiOperation(value = "获取消息服务器地址")
    @PostMapping("/getSvrAddr")
    public ResultDto<String> getSvrAddr() {
        ResultDto<String> result =new  ResultDto<String>();
        try {
            Properties pro=  ProsUtils.getProperty(serverProPath);
            int serverCount=pro.size();
            Random r = new Random();
            int index = r.nextInt(serverCount);
            int i=0;
            for (String name: pro.stringPropertyNames()){
                 if(i==index)
                 {
                     String svrAddr= pro.getProperty(name);
                     result.setFirstParam("ws://"+svrAddr);
                     break;
                 }
                 i++;
            }
            result.setStatus(1);
            result.setMessage("Request Is Success");

        }catch (Exception e) {
            //TODO: handle exception
            result.setStatus(500);
            result.setMessage("/Dev/getSvrAddr Server Error");
            result.setFirstParam(null);
        }
        return  result;
    }

    @ApiOperation(value = "获取200条预备数据")
    @PostMapping("/getPreheatData")
    public ResultDto<ArrayList<Preheat_Response>> getPreheatData(@RequestBody Preheat_Request request)
    {
        ResultDto<ArrayList<Preheat_Response>> result =new  ResultDto<ArrayList<Preheat_Response>>();
        try {
            Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            ArrayList<Preheat_Response> data=new ArrayList<Preheat_Response>();
            for (String itemID:request.getItemIDs()) {
                Preheat_Response pInfo=new Preheat_Response();
                String tempKey = DevSignalWebSocket.getPushDataKey(pushDataKey, request.getSTCD(),itemID);
                String dataListString = redisTampate.get(tempKey);
                ArrayList<YY_DATA_AUTO_Request> list= gson.fromJson(dataListString,new TypeToken<ArrayList<YY_DATA_AUTO_Request>>(){}.getType());
                pInfo.setItemID(itemID);
                pInfo.setList(list);
                data.add(pInfo);
            }
            result.setFirstParam(data);
            result.setStatus(1);
            result.setMessage("Request Is Success");

        }catch (Exception e) {
            //TODO: handle exception
            result.setStatus(500);
            result.setMessage("/Dev/getPreheatData Server Error");
            result.setFirstParam(null);
        }
        return  result;

    }


    private static void sort(List<YY_DATA_AUTO_Request> list) {
            Collections.sort(list,new Comparator<YY_DATA_AUTO_Request>() {
                @Override
                public int compare(YY_DATA_AUTO_Request o1, YY_DATA_AUTO_Request o2) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try{
                        if (o1.getTM().getTime() > o2.getTM().getTime()) {
                            return 1;
                        } else if (o1.getTM().getTime() < o2.getTM().getTime()) {
                            return -1;
                        } else {
                            return 0;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return 0;
                }
            });
    }


}
